{% extends "rbac/base.html" %}

{% block title %}用户管理 - RBAC权限管理系统{% endblock %}

{% block extra_css %}
<style>
/* 用户管理页面专用样式 */
.user-table {
    border-collapse: separate;
    border-spacing: 0;
}

.user-table thead th {
    background-color: #f8f9fa;
    border-bottom: 2px solid #dee2e6;
    font-weight: 600;
}

.user-table tbody tr:hover {
    background-color: rgba(13, 110, 253, 0.05);
}

.user-table th, .user-table td {
    padding: 1rem;
    vertical-align: middle;
}

.user-name {
    font-weight: 500;
}

.user-email {
    color: #6c757d;
    font-size: 0.875rem;
}

.user-fullname {
    font-size: 0.875rem;
}

.user-roles-count {
    display: inline-block;
    min-width: 30px;
    text-align: center;
}

.user-status-badge {
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
}

.user-actions .btn {
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
    margin-right: 0.25rem;
}

.user-actions .btn:last-child {
    margin-right: 0;
}

.empty-state {
    padding: 3rem 2rem;
    text-align: center;
}

.search-container {
    max-width: 300px;
}

/* 响应式优化 */
@media (max-width: 768px) {
    .user-table th, .user-table td {
        padding: 0.75rem 0.5rem;
    }
    
    .user-email, .user-fullname {
        display: none;
    }
    
    .user-actions .btn span {
        display: none;
    }
    
    .user-actions .btn i {
        margin-right: 0;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <!-- 页面标题区 -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h2 class="mb-1"><i class="fas fa-users text-primary me-2"></i>用户管理</h2>
                    <p class="text-muted mb-0">管理系统用户和角色分配</p>
                </div>
                {% if can_add_user %}
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
                        <i class="fas fa-plus me-1"></i>添加用户
                    </button>
                </div>
                {% endif %}
            </div>
            
            <!-- 消息提示 -->
            {% if messages %}
                {% for message in messages %}
                    <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                        <i class="fas fa-info-circle me-2"></i>{{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                {% endfor %}
            {% endif %}
            
            <!-- 用户列表 -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center">
                            <h5 class="mb-0 text-dark">
                                <i class="fas fa-list me-2 text-primary"></i>用户列表
                            </h5>
                            <span class="badge bg-light text-dark ms-2">{{ users_with_roles|length }} 个用户</span>
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            <div class="input-group search-container">
                                <span class="input-group-text bg-light border-end-0">
                                    <i class="fas fa-search text-muted"></i>
                                </span>
                                <input type="text" class="form-control border-start-0" id="userSearchInput" 
                                       placeholder="搜索用户名或邮箱...">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    {% if users_with_roles %}
                        <div class="table-responsive">
                            <table class="table user-table mb-0">
                                <thead>
                                    <tr>
                                        <th>用户名</th>
                                        <th>邮箱</th>
                                        <th>姓名</th>
                                        <th>角色</th>
                                        <th>状态</th>
                                        {% if can_edit_user or can_delete_user %}
                                        <th>操作</th>
                                        {% endif %}
                                    </tr>
                                </thead>
                                <tbody id="userTableBody">
                                    {% for user_data in users_with_roles %}
                                    <tr class="user-row" data-username="{{ user_data.user.username|lower }}" data-email="{{ user_data.user.email|lower }}">
                                        <td>
                                            <div class="user-name">
                                                {% if user_data.user.is_superuser %}
                                                    <i class="fas fa-crown text-warning me-1"></i>
                                                {% else %}
                                                    <i class="fas fa-user text-secondary me-1"></i>
                                                {% endif %}
                                                {{ user_data.user.username }}
                                            </div>
                                        </td>
                                        <td>
                                            <div class="user-email">{{ user_data.user.email }}</div>
                                        </td>
                                        <td>
                                            <div class="user-fullname">{{ user_data.user.get_full_name|default:"未设置" }}</div>
                                        </td>
                                        <td>
                                            {% if user_data.roles %}
                                                {% for role in user_data.roles %}
                                                    <span class="badge bg-{% if role.code == 'super_admin' %}danger{% elif role.code == 'admin' %}primary{% elif role.code == 'department_manager' %}warning{% else %}secondary{% endif %} me-1">
                                                        {{ role.name }}
                                                    </span>
                                                {% endfor %}
                                            {% else %}
                                                <span class="badge bg-light text-dark">无角色</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if user_data.user.is_active %}
                                                <span class="badge bg-success user-status-badge">
                                                    <i class="fas fa-check me-1"></i>活跃
                                                </span>
                                            {% else %}
                                                <span class="badge bg-danger user-status-badge">
                                                    <i class="fas fa-times me-1"></i>禁用
                                                </span>
                                            {% endif %}
                                        </td>
                                        {% if can_edit_user or can_delete_user %}
                                        <td class="user-actions">
                                            {% if can_edit_user %}
                                                <button type="button" class="btn btn-primary btn-sm" 
                                                        data-bs-toggle="modal" data-bs-target="#editModal"
                                                        data-user-id="{{ user_data.user.id }}"
                                                        data-username="{{ user_data.user.username }}"
                                                        data-email="{{ user_data.user.email }}"
                                                        data-first-name="{{ user_data.user.first_name }}"
                                                        data-last-name="{{ user_data.user.last_name }}"
                                                        data-user-roles="{% for role in user_data.roles %}{{ role.id }}{% if not forloop.last %},{% endif %}{% endfor %}">
                                                    <i class="fas fa-edit me-1"></i><span>编辑</span>
                                                </button>
                                            {% endif %}
                                            {% if can_delete_user and user_data.user.id != current_user.id %}
                                                <form method="POST" style="display: inline;" 
                                                      onsubmit="return confirm('确定要删除该用户吗？此操作不可恢复！')">
                                                    {% csrf_token %}
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="user_id" value="{{ user_data.user.id }}">
                                                    <button type="submit" class="btn btn-outline-danger btn-sm">
                                                        <i class="fas fa-trash me-1"></i><span>删除</span>
                                                    </button>
                                                </form>
                                            {% endif %}
                                        </td>
                                        {% endif %}
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="text-center py-5">
                            <div class="empty-state">
                                <i class="fas fa-users-slash fa-4x text-muted mb-3"></i>
                                <h5 class="text-muted mb-2">暂无用户数据</h5>
                                <p class="text-muted mb-4">系统中还没有创建任何用户，点击下方按钮开始创建</p>
                                {% if can_add_user %}
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
                                    <i class="fas fa-plus me-1"></i>创建第一个用户
                                </button>
                                {% endif %}
                            </div>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加用户模态框 -->
{% if can_add_user %}
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white border-0">
                <h5 class="modal-title" id="addModalLabel">
                    <i class="fas fa-user-plus me-2"></i>添加新用户
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <form method="POST">
                    {% csrf_token %}
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label for="add_username" class="form-label fw-medium">
                            <i class="fas fa-user-tag text-primary me-1"></i>用户名 
                            <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control form-control-lg" id="add_username" 
                               name="username" placeholder="请输入用户名" required>
                        <div class="form-text">用于登录系统的唯一标识</div>
                    </div>
                    <div class="mb-3">
                        <label for="add_email" class="form-label fw-medium">
                            <i class="fas fa-envelope text-info me-1"></i>邮箱 
                            <span class="text-danger">*</span>
                        </label>
                        <input type="email" class="form-control form-control-lg" id="add_email" 
                               name="email" placeholder="请输入邮箱地址" required>
                        <div class="form-text">用于接收系统通知和密码重置</div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="add_first_name" class="form-label fw-medium">
                                <i class="fas fa-signature text-secondary me-1"></i>名
                            </label>
                            <input type="text" class="form-control" id="add_first_name" 
                                   name="first_name" placeholder="请输入名">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="add_last_name" class="form-label fw-medium">
                                <i class="fas fa-signature text-secondary me-1"></i>姓
                            </label>
                            <input type="text" class="form-control" id="add_last_name" 
                                   name="last_name" placeholder="请输入姓">
                        </div>
                    </div>
                    {% if can_manage_roles %}
                    <div class="mb-3">
                        <label class="form-label fw-medium">
                            <i class="fas fa-user-tag text-warning me-1"></i>角色分配
                        </label>
                        <div class="row g-2">
                            {% for role in active_roles %}
                            <div class="col-md-6">
                                <div class="form-check p-3 bg-white border rounded">
                                    <input class="form-check-input" type="checkbox" 
                                           value="{{ role.id }}" name="roles" id="add_role_{{ role.id }}">
                                    <label class="form-check-label w-100" for="add_role_{{ role.id }}">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong class="text-dark">{{ role.name }}</strong>
                                            {% if role.is_system %}
                                                <span class="badge bg-primary bg-opacity-10 text-primary">
                                                    <i class="fas fa-cog"></i>
                                                </span>
                                            {% endif %}
                                        </div>
                                        {% if role.description %}
                                        <small class="text-muted d-block mt-1">{{ role.description }}</small>
                                        {% endif %}
                                        <code class="small text-primary mt-1 d-block">{{ role.code }}</code>
                                    </label>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    {% endif %}
                    <div class="mb-0">
                        <label for="add_password" class="form-label fw-medium">
                            <i class="fas fa-lock text-danger me-1"></i>密码 
                            <span class="text-danger">*</span>
                        </label>
                        <input type="password" class="form-control form-control-lg" id="add_password" 
                               name="password" placeholder="请输入密码" required>
                        <div class="form-text">密码长度至少8位，建议包含字母、数字和特殊字符</div>
                    </div>
                </div>
                <div class="modal-footer border-0 bg-light">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>取消
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i>保存用户
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endif %}

<!-- 编辑用户模态框 -->
{% if can_edit_user %}
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white border-0">
                <h5 class="modal-title" id="editModalLabel">
                    <i class="fas fa-user-edit me-2"></i>编辑用户
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <form method="POST">
                    {% csrf_token %}
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="user_id" id="edit_user_id">
                    <div class="mb-3">
                        <label for="edit_username" class="form-label fw-medium">
                            <i class="fas fa-user-tag text-primary me-1"></i>用户名 
                            <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control form-control-lg" id="edit_username" 
                               name="username" placeholder="请输入用户名" required>
                        <div class="form-text">用于登录系统的唯一标识</div>
                    </div>
                    <div class="mb-3">
                        <label for="edit_email" class="form-label fw-medium">
                            <i class="fas fa-envelope text-info me-1"></i>邮箱 
                            <span class="text-danger">*</span>
                        </label>
                        <input type="email" class="form-control form-control-lg" id="edit_email" 
                               name="email" placeholder="请输入邮箱地址" required>
                        <div class="form-text">用于接收系统通知和密码重置</div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="edit_first_name" class="form-label fw-medium">
                                <i class="fas fa-signature text-secondary me-1"></i>名
                            </label>
                            <input type="text" class="form-control" id="edit_first_name" 
                                   name="first_name" placeholder="请输入名">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="edit_last_name" class="form-label fw-medium">
                                <i class="fas fa-signature text-secondary me-1"></i>姓
                            </label>
                            <input type="text" class="form-control" id="edit_last_name" 
                                   name="last_name" placeholder="请输入姓">
                        </div>
                    </div>
                    {% if can_manage_roles %}
                    <div class="mb-3">
                        <label class="form-label fw-medium">
                            <i class="fas fa-user-tag text-warning me-1"></i>角色分配
                        </label>
                        <div class="row g-2">
                            {% for role in active_roles %}
                            <div class="col-md-6">
                                <div class="form-check p-3 bg-white border rounded">
                                    <input class="form-check-input edit-role-checkbox" type="checkbox" 
                                           value="{{ role.id }}" name="roles" id="edit_role_{{ role.id }}">
                                    <label class="form-check-label w-100" for="edit_role_{{ role.id }}">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong class="text-dark">{{ role.name }}</strong>
                                            {% if role.is_system %}
                                                <span class="badge bg-primary bg-opacity-10 text-primary">
                                                    <i class="fas fa-cog"></i>
                                                </span>
                                            {% endif %}
                                        </div>
                                        {% if role.description %}
                                        <small class="text-muted d-block mt-1">{{ role.description }}</small>
                                        {% endif %}
                                        <code class="small text-primary mt-1 d-block">{{ role.code }}</code>
                                    </label>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    {% endif %}
                    <div class="mb-0">
                        <label for="edit_password" class="form-label fw-medium">
                            <i class="fas fa-lock text-danger me-1"></i>密码
                        </label>
                        <input type="password" class="form-control form-control-lg" id="edit_password" 
                               name="password" placeholder="留空则不修改密码">
                        <div class="form-text">密码长度至少8位，建议包含字母、数字和特殊字符</div>
                    </div>
                </div>
                <div class="modal-footer border-0 bg-light">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>取消
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i>保存用户
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endif %}

{% endblock %}

{% block extra_js %}
<script>
// 编辑模态框数据填充
const editModal = document.getElementById('editModal');
if (editModal) {
    editModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const userId = button.getAttribute('data-user-id');
        const username = button.getAttribute('data-username');
        const email = button.getAttribute('data-email');
        const firstName = button.getAttribute('data-first-name');
        const lastName = button.getAttribute('data-last-name');
        const userRoles = button.getAttribute('data-user-roles');
        
        // 填充基本信息
        document.getElementById('edit_user_id').value = userId;
        document.getElementById('edit_username').value = username;
        document.getElementById('edit_email').value = email;
        document.getElementById('edit_first_name').value = firstName || '';
        document.getElementById('edit_last_name').value = lastName || '';
        
        // 清除所有角色选中状态
        document.querySelectorAll('.edit-role-checkbox').forEach(cb => cb.checked = false);
        
        // 设置用户的角色
        if (userRoles) {
            const roleIds = userRoles.split(',');
            roleIds.forEach(function(roleId) {
                if (roleId.trim()) {
                    const checkbox = document.getElementById('edit_role_' + roleId.trim());
                    if (checkbox) checkbox.checked = true;
                }
            });
        }
    });
}

// 用户搜索功能
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('userSearchInput');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();
            const userRows = document.querySelectorAll('.user-row');
            
            userRows.forEach(row => {
                const username = row.dataset.username || '';
                const email = row.dataset.email || '';
                
                if (username.includes(searchTerm) || email.includes(searchTerm)) {
                    row.style.display = 'table-row';
                } else {
                    row.style.display = 'none';
                }
            });
        });
    }
    
    console.log('🎉 用户管理页面初始化完成');
});
</script>
{% endblock %}